package bupt.party.online.action;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import bupt.party.online.model.Admin;
import bupt.party.online.model.Branch;
import bupt.party.online.model.BranchNews;
import bupt.party.online.model.LearnRecord;
import bupt.party.online.model.Student;
import bupt.party.online.service.IAdminService;
import bupt.party.online.service.IBranchNewsService;
import bupt.party.online.service.IBranchService;
import bupt.party.online.service.ILearnRecordService;
import bupt.party.online.service.IStudentService;
import bupt.party.online.util.SessionConstants;

import com.opensymphony.xwork2.ActionContext;

public class MyBranchAction extends Pagination implements ServletRequestAware, ServletResponseAware{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//branchSummary
	private Branch branch;
	private int countBranch;
	
	//branchNotice
	private BranchNews branchNews;
	private List<BranchNews> branchNewsList;
	private List<Branch> chargeBranches = new ArrayList<Branch>();
	//branchMember
	private LearnRecord learnRecord;
	private List<Student> studentList;
	
	//listParty
	private List<Branch> firstPaList = new ArrayList<Branch>();  //代表一级结构的列表
	private List<Branch> secondPaList = new ArrayList<Branch>(); //代表二级结构的列表
	private Integer parentId;   //第一级或者第二级的党委id
	private String xmlString;   //生成二级和三级党委结构的数据信息
	private Integer firstPa = -1;  //一级党委id
    private Integer secondPa = -1;  //二级党委id
    private HttpServletRequest request;
    private HttpServletResponse response;
    private List<Branch> children;
    
    //新的branchList
    private String branchId;
    private List<Branch> list;
    
    //addBranch
    private File branchPic;
	private String branchPicFileName;
	private String branchPicContentType;
	private static String RealBranchPicPath = ServletActionContext.getServletContext().getRealPath("/images/branchImage");
	private static String ServerBranchPicPath = "/images/branchImage";
	
	//依赖注入
	private IBranchService branchService;
	private IBranchNewsService branchNewsService;
	private ILearnRecordService learnRecordService;
	private IStudentService studentService;
	private String paginationCode;
	private IAdminService adminService;
	// for view news
	private int id;
	private BranchNews currentNews;
	private String titleOnQuery;
		
	//for new party news
	private String title;
	private String content;
	
	
	public List<Branch> getChargeBranches() {
		return chargeBranches;
	}
	public void setChargeBranches(List<Branch> chargeBranches) {
		this.chargeBranches = chargeBranches;
	}
	public IAdminService getAdminService() {
		return adminService;
	}
	public void setAdminService(IAdminService adminService) {
		this.adminService = adminService;
	}
	public File getBranchPic() {
		return branchPic;
	}
	public void setBranchPic(File branchPic) {
		this.branchPic = branchPic;
	}
	public String getBranchPicFileName() {
		return branchPicFileName;
	}
	public void setBranchPicFileName(String branchPicFileName) {
		this.branchPicFileName = branchPicFileName;
	}
	public String getBranchPicContentType() {
		return branchPicContentType;
	}
	public void setBranchPicContentType(String branchPicContentType) {
		this.branchPicContentType = branchPicContentType;
	}
	public static String getRealBranchPicPath() {
		return RealBranchPicPath;
	}
	public static void setRealBranchPicPath(String realBranchPicPath) {
		RealBranchPicPath = realBranchPicPath;
	}
	public static String getServerBranchPicPath() {
		return ServerBranchPicPath;
	}
	public static void setServerBranchPicPath(String serverBranchPicPath) {
		ServerBranchPicPath = serverBranchPicPath;
	}
	public HttpServletRequest getRequest() {
		return request;
	}
	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}
	public HttpServletResponse getResponse() {
		return response;
	}
	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	public String getTitleOnQuery() {
		return titleOnQuery;
	}
	public void setTitleOnQuery(String titleOnQuery) {
		this.titleOnQuery = titleOnQuery;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public List<Student> getStudentList() {
		return studentList;
	}
	public void setStudentList(List<Student> studentList) {
		this.studentList = studentList;
	}
	public IStudentService getStudentService() {
		return studentService;
	}
	public void setStudentService(IStudentService studentService) {
		this.studentService = studentService;
	}
	public String getBranchId() {
		return branchId;
	}
	public void setBranchId(String branchId) {
		this.branchId = branchId;
	}
	public List<Branch> getList() {
		return list;
	}
	public void setList(List<Branch> list) {
		this.list = list;
	}
	public List<Branch> getChildren() {
		return children;
	}
	public void setChildren(List<Branch> children) {
		this.children = children;
	}
	public List<Branch> getFirstPaList() {
		return firstPaList;
	}
	public void setFirstPaList(List<Branch> firstPaList) {
		this.firstPaList = firstPaList;
	}
	public List<Branch> getSecondPaList() {
		return secondPaList;
	}
	public void setSecondPaList(List<Branch> secondPaList) {
		this.secondPaList = secondPaList;
	}
	public Integer getParentId() {
		return parentId;
	}
	public void setParentId(Integer parentId) {
		this.parentId = parentId;
	}
	public String getXmlString() {
		return xmlString;
	}
	public void setXmlString(String xmlString) {
		this.xmlString = xmlString;
	}
	public Integer getFirstPa() {
		return firstPa;
	}
	public void setFirstPa(Integer firstPa) {
		this.firstPa = firstPa;
	}
	public Integer getSecondPa() {
		return secondPa;
	}
	public void setSecondPa(Integer secondPa) {
		this.secondPa = secondPa;
	}
	public LearnRecord getLearnRecord() {
		return learnRecord;
	}
	public void setLearnRecord(LearnRecord learnRecord) {
		this.learnRecord = learnRecord;
	}
	public ILearnRecordService getLearnRecordService() {
		return learnRecordService;
	}
	public void setLearnRecordService(ILearnRecordService learnRecordService) {
		this.learnRecordService = learnRecordService;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public BranchNews getCurrentNews() {
		return currentNews;
	}
	public void setCurrentNews(BranchNews currentNews) {
		this.currentNews = currentNews;
	}
	public String getPaginationCode() {
		return paginationCode;
	}
	public void setPaginationCode(String paginationCode) {
		this.paginationCode = paginationCode;
	}
	public List<BranchNews> getBranchNewsList() {
		return branchNewsList;
	}
	public void setBranchNewsList(List<BranchNews> branchNewsList) {
		this.branchNewsList = branchNewsList;
	}
	public int getCountBranch() {
		return countBranch;
	}
	public void setCountBranch(int countBranch) {
		this.countBranch = countBranch;
	}
	public Branch getBranch() {
		return branch;
	}
	public void setBranch(Branch branch) {
		this.branch = branch;
	}
	public BranchNews getBranchNews() {
		return branchNews;
	}
	public void setBranchNews(BranchNews branchNews) {
		this.branchNews = branchNews;
	}
	public IBranchService getBranchService() {
		return branchService;
	}
	public void setBranchService(IBranchService branchService) {
		this.branchService = branchService;
	}
	public IBranchNewsService getBranchNewsService() {
		return branchNewsService;
	}
	public void setBranchNewsService(IBranchNewsService branchNewsService) {
		this.branchNewsService = branchNewsService;
	}
	public String branchSummary(){
		HttpSession session = request.getSession();
		Student session_student = (Student)session.getAttribute(SessionConstants.SESSION_USER);
		
		int bId= session_student.getStudentBranchId();
		Branch branch=branchService.findBranchById(bId);
		countBranch=this.studentService.getStudentCountByBranchId(bId);
		if(branch!=null){
			setBranch(branch);
		}
		return "branchSummary";
	}
	public String branchMember(){
		
		HttpSession session = request.getSession();
		Student session_student = (Student)session.getAttribute(SessionConstants.SESSION_USER);
		
		int id =session_student.getStudentBranchId();
		
		String nameBranch = this.branchService.getBranchName(id);
		request.setAttribute("nameBranch", nameBranch);
		
		//分页
	    if(this.pageNow == null) pageNow = 1;		
		totalResults = 0;		
		paginationCode = "";
			
		totalResults = this.studentService.getStudentCountByBranchId(id);
		this.pageCount = (totalResults % pageSize == 0) ? totalResults
				/ pageSize : totalResults / pageSize + 1;
		studentList = this.studentService.QueryStudentByBranchId(id, pageNow, pageSize);
		if (totalResults > 0){
			//this.setPageSize(5);
			paginationCode = Pagination.getPaginationCode(pageSize,
					totalResults, pageNow);
		}		
		else
			paginationCode = "没有查询到有效数据！";
	    
	    
		pageNow=null;
		
		return "branchMember";
	}
	public String branchNotice(){

		HttpSession session = request.getSession();
		
		Student session_student = (Student)session.getAttribute(SessionConstants.SESSION_USER);
		
		if(session_student == null) return "error";
		
		if(pageNow == null) titleOnQuery="";
		
		Map<String,Object> conditions = new HashMap<String,Object>();
		
		if(this.titleOnQuery != null && this.titleOnQuery.trim() != "") conditions.put("title", "%"+titleOnQuery+"%");
		
		conditions.put("branchId", session_student.getStudentBranchId());
		
		conditions.put("tag", 1);
		
		this.newsExecution(conditions);
		
		pageNow = null;
		
		request.setAttribute("titleOnQuery", titleOnQuery);
		
		return "branchNotice";
	}
	
	public String branchActivity(){

		HttpServletRequest request = ServletActionContext.getRequest();
		
		HttpSession session = request.getSession();
		
		Student session_student = (Student)session.getAttribute(SessionConstants.SESSION_USER);
		
		if(session_student == null) return "error";
		
		if(pageNow == null) titleOnQuery="";
		
		Map<String,Object> conditions = new HashMap<String,Object>();
		
		if(this.titleOnQuery != null && this.titleOnQuery.trim() != "") conditions.put("title", "%"+titleOnQuery+"%");
		
		conditions.put("branchId", session_student.getStudentBranchId());
		
		conditions.put("tag", 2);
		
		this.newsExecution(conditions);
		
		pageNow = null;
		
		request.setAttribute("titleOnQuery", titleOnQuery);
		
		return "branchActivity";
	}
	public String listParty(){
		HttpSession session = request.getSession();
		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 
		
		if(!(user instanceof Admin)) return "loginUI";
		
	    firstPaList = branchService.findParentBranches();
		secondPaList = new ArrayList<Branch>();
	    
		//分页
	    if(this.pageNow == null ) pageNow = 1;		
		totalResults = 0;		
		paginationCode = "";
		
		branchId = request.getParameter("firstPa");
	    if(branchId!=null){
	    	int parent=Integer.parseInt(branchId);
	    	totalResults = this.branchService.getResultCountByTag(parent);
			this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
			children = this.branchService.getNewsByCategory(parent, pageNow, pageSize);
			if(totalResults > 0) paginationCode = Pagination.getPaginationCode(pageSize, totalResults, pageNow);
			else paginationCode = "没有查询到有效数据！";
			
	    }else{
	    	
	    	totalResults = this.branchService.getResultCount();
			this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
			children = this.branchService.getNewsByCategory(-2, pageNow, pageSize);
			if(totalResults > 0) paginationCode = Pagination.getPaginationCode(pageSize, totalResults, pageNow);
			else paginationCode = "没有查询到有效数据！";
	    }
	    
	    
		
		this.getSession().put("firstPa", firstPa);
		this.getSession().put("secondPa", secondPa);
	    
		
		
		return "listParty";
	}
	public String branchList(){
		HttpSession session = request.getSession();
		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 
		
		if(!(user instanceof Admin)) return "loginUI";
		
		Admin admin	 = (Admin) user;
		
		if(admin.getAdminLevel()==3){//一级支部
			
			branchId=request.getParameter("branchId");			
			if(branchId==null){
				list = new ArrayList<Branch>();
				list.add(this.branchService.findBranchById(1));
			}else{
				list = new ArrayList<Branch>();
				int parentId = Integer.parseInt(branchId);
				list = this.branchService.findChildBranchesById(parentId);
			}
			
		}else if(admin.getAdminLevel()==2){//二级支部
			
			branchId=request.getParameter("branchId");
			if(branchId==null || branchId.equals("1")){
				list = new ArrayList<Branch>();
				list.add(this.branchService.findBranchById(admin.getAdminManageBranchId()));
			}else{
				list = new ArrayList<Branch>();
				int parentId = Integer.parseInt(branchId);
				list = this.branchService.findChildBranchesById(parentId);
			}
			
		}else {//三级支部		
			
			branchId=request.getParameter("branchId");
			if(branchId!=null){
				if(Integer.parseInt(branchId)!=admin.getAdminManageBranchId())return "noPermission";
			}
		
			list = new ArrayList<Branch>();
			list.add(this.branchService.findBranchById(admin.getAdminManageBranchId()));
		}
		if(list!=null){
			request.setAttribute("branchSize", list.size());
		}else{
			request.setAttribute("branchSize", 0);
		}
		
		return "branchList";
	}
	//根据支部id计算支部下人数
	public int getCountStudentByBranchId(int id){
		int count = this.studentService.getStudentCountByBranchId(id);
		return count;
	}
	
	public int hasChild(int id){
		if(this.branchService.findChildBranchesById(id)!=null){
			return 1;
		}
		return 0;
	}
	
	public String getChildrenPaByParentId() {
		//获得session对象
		HttpServletRequest request = ServletActionContext.getRequest(); 
		HttpSession session = request.getSession();
		
		List<Branch> list = branchService.findChildBranchesById(parentId);
		StringBuffer sb = new StringBuffer("<alibranches>");
		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		
		for(Iterator<Branch> it = list.iterator(); it.hasNext(); ) {
			Branch AlipaBranch = it.next();
			sb.append("<id>");
			sb.append(AlipaBranch.getId());
			sb.append("</id>");
			sb.append("<name>");
			sb.append(AlipaBranch.getBranchName());
			sb.append("</name>");
		}
		
		sb.append("</alibranches>");
		xmlString = sb.toString();
		try {
			response.getWriter().write(xmlString);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	} 
	
	
	public String addBranch(){
		
		HttpSession session = request.getSession();
		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 
		
		if(!(user instanceof Admin)) return "loginUI";
		
		Admin admin	 = (Admin) user;
		
		if(admin.getAdminLevel()==1){//三级支部
			return "noPermission";
		}else if(admin.getAdminLevel()==2){//二级支部
			firstPaList = new ArrayList<Branch>();
			firstPaList.add(this.branchService.findBranchById(admin.getAdminManageBranchId()));
		}else{//一级支部
			firstPaList = new ArrayList<Branch>();
			firstPaList.add(this.branchService.findBranchById(1));
			firstPaList.addAll(branchService.findParentBranches());		
		}	
		return "addBranch";
	}
	
	public String addRealBranch() throws ParseException{
		
		String branchName=request.getParameter("branchName");
		String branchSecretaryName=request.getParameter("branchSecretaryName");
		String branchViceSecretaryName=request.getParameter("branchViceSecretaryName");
		String createTimes =request.getParameter("createTime");
		String organizationName= request.getParameter("organizationName");
		String unitedName= request.getParameter("unitedName");
		String massesName= request.getParameter("massesName");
		String confidentialityName= request.getParameter("confidentialityName");
		String youthName= request.getParameter("youthName");
		String disciplineName= request.getParameter("disciplineName");
		String publicityName= request.getParameter("publicityName");
		String branchHonor= request.getParameter("branchHonor");
		String branchSummary= request.getParameter("branchSummary");
		Integer isDelete = 0;
		Integer parentId = Integer.parseInt(request.getParameter("firstPa"));
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse(createTimes);
		Timestamp createTime = new Timestamp(date.getTime());
		
		//上传照片
		String picFileName=null;
		if(branchPic != null ){//无照片
			String suffix = this.getBranchPicFileName().substring(this.getBranchPicFileName().lastIndexOf(".") + 1);
			picFileName = this.createFilename(suffix);
			try {
				FileUtils.copyFile(branchPic, new File(MyBranchAction.RealBranchPicPath+File.separator+picFileName));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		
		branch = new Branch();
		branch.setBranchName(branchName);
		if(branchPic !=null){
			branch.setBranchPic(this.ServerBranchPicPath+"/"+picFileName);
		}
		branch.setBranchSecretaryName(branchSecretaryName);
		branch.setBranchViceSecretaryName(branchViceSecretaryName);
		branch.setCreateTime(createTime);
		branch.setOrganizationName(organizationName);
		branch.setUnitedName(unitedName);
		branch.setMassesName(massesName);
		branch.setConfidentialityName(confidentialityName);
		branch.setYouthName(youthName);
		branch.setDisciplineName(disciplineName);
		branch.setPublicityName(publicityName);
		branch.setBranchHonor(branchHonor);
		branch.setBranchSummary(branchSummary);
		branch.setParentId(parentId);
		branch.setIsDelete(0);
		if(parentId==1){
			branch.setLevel(2);
		}else {
			branch.setLevel(3);
		}
		
		
		this.branchService.addBranch(branch);
		return "success";
	}
	
	public  String createFilename(String suffix)
	{
		Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DATE);
		int hour = calendar.get(Calendar.HOUR);
		int minute = calendar.get(Calendar.MINUTE);
		int second = calendar.get(Calendar.SECOND);
		
		String filename = year + "_" + month + "_"+ day + "_" + hour + "_" + minute + "_" + second + "_branchPic." + suffix;
		return filename;
	}
	
	public String updateBranch(){
		
		HttpSession session = request.getSession();
		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 
		
		if(!(user instanceof Admin)) return "loginUI";
		
		Admin admin	 = (Admin) user;
		//使得管理员level与支部level平级
		int level = admin.getAdminLevel();
		if(level==3){
			level=1;
		}else if(level==1){
			level=3;
		}
		request.setAttribute("level", level);
		branch = this.branchService.findBranchById(Integer.parseInt(request.getParameter("id")));
		return "updateBranch";
	}
	public String updateRealBranch() throws ParseException{
		
		String branchName=request.getParameter("branchName");
		if(branchName==null) return "fail";
		String branchSecretaryName=request.getParameter("branchSecretaryName");
		String branchViceSecretaryName=request.getParameter("branchViceSecretaryName");
		String createTimes =request.getParameter("createTime");
		String organizationName= request.getParameter("organizationName");
		String unitedName= request.getParameter("unitedName");
		String massesName= request.getParameter("massesName");
		String confidentialityName= request.getParameter("confidentialityName");
		String youthName= request.getParameter("youthName");
		String disciplineName= request.getParameter("disciplineName");
		String publicityName= request.getParameter("publicityName");
		String branchHonor= request.getParameter("branchHonor");
		String branchSummary= request.getParameter("branchSummary");
		Integer isDelete = 0;
		Integer id = Integer.parseInt(request.getParameter("id"));
		
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date = format.parse(createTimes);
		Timestamp createTime = new Timestamp(date.getTime());
		
		//图片
		String picFileName=null;
		if(branchPic != null  ) {
			String suffix = this.getBranchPicFileName().substring(this.getBranchPicFileName().lastIndexOf(".") + 1);
			picFileName = this.createFilename(suffix);
			try {
				FileUtils.copyFile(branchPic, new File(MyBranchAction.RealBranchPicPath+File.separator+picFileName));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		branch = this.branchService.findBranchById(id);
		branch.setBranchName(branchName);
		if(branchPic !=null ){
			if(branch.getBranchPic()!=""&&branch.getBranchPic()!=null){
				File f = new File(branch.getBranchPic());
				f.delete();
			}	
			branch.setBranchPic(this.ServerBranchPicPath+"/"+picFileName);
		}
		branch.setBranchSecretaryName(branchSecretaryName);
		branch.setBranchViceSecretaryName(branchViceSecretaryName);
		branch.setCreateTime(createTime);
		branch.setOrganizationName(organizationName);
		branch.setUnitedName(unitedName);
		branch.setMassesName(massesName);
		branch.setConfidentialityName(confidentialityName);
		branch.setYouthName(youthName);
		branch.setDisciplineName(disciplineName);
		branch.setPublicityName(publicityName);
		branch.setBranchHonor(branchHonor);
		branch.setBranchSummary(branchSummary);
		this.branchService.updateBranch(branch);
		
		branchPic = null;
		
		return "success";
	}
	
	public String deleteBranch(){
		branch = this.branchService.findBranchById(Integer.parseInt(request.getParameter("id")));
		request.setAttribute("deleteId", branch.getParentId());
		request.setAttribute("tag", 3);
		this.branchService.deleteBranchById(branch.getId());
		return "success";
	}
	
	public String manageBranch(){
		return "branchList";
	}
	public String browseBranch(){
		
		HttpSession session = request.getSession();		
		Object user = session.getAttribute(SessionConstants.SESSION_USER); 		
		if(!(user instanceof Admin)) return "loginUI";		
		Admin admin	 = (Admin) user;
		branch = this.branchService.findBranchById(Integer.parseInt(request.getParameter("id")));
		return "browseBranch";
	}
	//获得session
    public Map getSession() {
		return ActionContext.getContext().getSession();
    }
	private void newsExecution(int categoryType){
		
		if(this.pageNow == null ) pageNow = 1;
		
		totalResults = 0;
		
		paginationCode = "";
		
		totalResults = this.branchNewsService.getResultCountByTag(categoryType);
		
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
		
		branchNewsList = this.branchNewsService.getNewsByCategory(categoryType, pageNow, pageSize);
		
		
		if(totalResults > 0) paginationCode = Pagination.getPaginationCode(pageSize, totalResults, pageNow);
		
		else paginationCode = "没有查询到有效数据！";
		
		pageNow = 1;
	}
	
	
	public  String viewNews(){
		if(id < 0) id = 0;
		currentNews = this.branchNewsService.findBranchNewsById(id);
		
		if(currentNews != null && currentNews.getVisitedCount() != null) {
			
			currentNews.setVisitedCount(currentNews.getVisitedCount()+1);
			//wangdong add a flag  
			int flag = currentNews.getTag();
			request.setAttribute("flag", flag);
			
			this.branchNewsService.saveOrUpdate(currentNews);
		}
		
		return "viewNews";
	}
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	public String manageBranchNotice(){

		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		
		branchService.getNodeChildrenBranches(branchService.findBranchById(admin.getAdminManageBranchId()), chargeBranches);
		
		if(pageNow == null) titleOnQuery="";
		
		Map<String,Object> conditions = new HashMap<String,Object>();
		
		if(this.titleOnQuery != null && this.titleOnQuery.trim() != "") conditions.put("title", "%"+titleOnQuery+"%");
		
		conditions.put("tag", 1);
		
		this.newsExecution(conditions);
		
		pageNow = null;
		
		request.setAttribute("titleOnQuery", titleOnQuery);
		
		return "manageBranchNotice";
	}
	
	public String manageBranchActivity(){

		HttpServletRequest request = ServletActionContext.getRequest();
		
		if(pageNow == null) titleOnQuery="";
		
		Map<String,Object> conditions = new HashMap<String,Object>();
		
		if(this.titleOnQuery != null && this.titleOnQuery.trim() != "") conditions.put("title", "%"+titleOnQuery+"%");
		
		conditions.put("tag", 2);
		
		this.newsExecution(conditions);
		
		pageNow = null;
		
		request.setAttribute("titleOnQuery", titleOnQuery);
		
		return "manageBranchActivity";
	}
	
	private void newsExecution(Map<String,Object> conditions){
		
		if(this.pageNow == null ) pageNow = 1;
		
		totalResults = 0;
		
		paginationCode = "";
		
		totalResults = this.branchNewsService.getResultCountByConditions(conditions);
		
		this.pageCount = (totalResults%pageSize == 0)?totalResults/pageSize : totalResults/pageSize + 1;
		
		branchNewsList = this.branchNewsService.getNewsByConditions(conditions, pageNow, pageSize);
		
		if(totalResults > 0) paginationCode = Pagination.getPaginationCode(pageSize, totalResults, pageNow);
		
		else paginationCode = "没有查询到有效数据！";
		
		request.setAttribute("modifyNewsPageNow", pageNow);
		
		pageNow = 1;
	}
	
	public String newBranchNotice(){
			//传给前台的是支部列表。。。。。wangdong
			HttpSession session = request.getSession();
			Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
				
			Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
			int branchId = admin.getAdminManageBranchId();
				
			//首先获得level 
			int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
			
			firstPa = -1;
			secondPa = -1;
			
			firstPaList.clear();
			
			if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
				//获得父亲的branchId(分党委id)
					
				Branch branch = branchService.getParentBranchById(branchId);//wangdong
				firstPaList.add(branch);
					
			}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
				
				Branch branch = branchService.findBranchById(branchId);
				firstPaList.add(branch);
			
			}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
				
				//获得所有的分党委list
				firstPaList = branchService.findChildBranchesById(branchId);	
				
			}
			
		   //wangdong
			request.setAttribute("flag", 1);
			
			return "newBranchNotice";
	}
	
	public String newBranchActivity(){
		//传给前台的是支部列表。。。。。wangdong
				HttpSession session = request.getSession();
				Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
				
				Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
				int branchId = admin.getAdminManageBranchId();
				
				//首先获得level 
				
				int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
				
				firstPa = -1;
				secondPa = -1;
				
				firstPaList.clear();
				
				if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
					//获得父亲的branchId(分党委id)
					
					Branch branch = branchService.getParentBranchById(branchId);//wangdong
					firstPaList.add(branch);
					
				}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
					
					Branch branch = branchService.findBranchById(branchId);
					firstPaList.add(branch);
				
				}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
					
					//获得所有的分党委list
					firstPaList = branchService.findChildBranchesById(branchId);	
					
				}
				
				//wangdong
				request.setAttribute("flag", 2);
				
				return "newBranchActivity";
	}
	
	public String saveBranchActivity(){
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		
		if(title == null || title.trim().length() <= 0) return "error";
		if(content == null || content.trim().length() <= 0) return "error";
		
		if(!admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL) && (secondPa == null || secondPa == -1)) return "error";
		
		if(!admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL) && this.branchService.findBranchById(secondPa) == null) return "error";
		
		BranchNews bean = new BranchNews();
		bean.setTitle(title);
		bean.setContent(content);
		bean.setIsDelete(0);
		bean.setPosterNo(admin.getAdminNo());
		bean.setPosterTime(new Timestamp(System.currentTimeMillis()));
		bean.setTag(2);
		bean.setVisitedCount(0);
		if(admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL)) bean.setBranchId(admin.getAdminManageBranchId());
		else bean.setBranchId(secondPa);
		if(!this.branchNewsService.saveOrUpdate(bean)) return "error";
		request.setAttribute("tag", 2);
		return "saveBranchActivity";
	}
	
	public String saveBranchNotice(){
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		
		if(title == null || title.trim().length() <= 0) return "error";
		if(content == null || content.trim().length() <= 0) return "error";
		if(!admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL) && (secondPa == null || secondPa == -1)) return "error";
		
		if(!admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL) && this.branchService.findBranchById(secondPa) == null) return "error";
		
		BranchNews bean = new BranchNews();
		bean.setTitle(title);
		bean.setContent(content);
		bean.setIsDelete(0);
		bean.setPosterNo(admin.getAdminNo());
		bean.setPosterTime(new Timestamp(System.currentTimeMillis()));
		bean.setTag(1);
		bean.setVisitedCount(0);
		if(admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL)) bean.setBranchId(admin.getAdminManageBranchId());
		else bean.setBranchId(secondPa);
		if(!this.branchNewsService.saveOrUpdate(bean)) return "error";
		request.setAttribute("tag", 1);
		return "saveBranchNotice";
	}
	
	public String modifyNews(){
		
		HttpServletRequest request = ServletActionContext.getRequest();
		
		HttpSession session = request.getSession();
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		int branchId = admin.getAdminManageBranchId();
		
		int modifyNewsPageNow = Integer.parseInt(request.getParameter("pageNow"));
		
		request.setAttribute("modifyNewsPageNow", modifyNewsPageNow);
		
		//首先获得level 
		int level = (Integer) session.getAttribute(SessionConstants.LEVEL);
		
		firstPaList.clear();
		
		Integer id = (request.getParameter("id") == null) ? null : Integer.parseInt(request.getParameter("id"));
		
		if(id == null) return "error";
		
		this.currentNews = this.branchNewsService.getNewsById(id);
		
		//wangdong add a flag  
		int flag = currentNews.getTag();
		request.setAttribute("flag", flag);
		
		secondPa = currentNews.getBranchId();
		
		Branch br = branchService.findBranchById(secondPa);
		
		firstPa = br.getParentId();
		
		secondPaList = branchService.findChildBranchesById(firstPa);
		
		if(level==SessionConstants.ADMIN_FIRST_LEVEL){//(1)支部管理员
			//获得父亲的branchId(分党委id)
			
			Branch branch = branchService.getParentBranchById(branchId);//wangdong
			firstPaList.add(branch);
			
		}else if(level==SessionConstants.ADMIN_SECOND_LEVEL){//(2)分党委管理员
			
			Branch branch = branchService.findBranchById(branchId);
			firstPaList.add(branch);
		
		}else if(level==SessionConstants.ADMIN_THIRD_LEVEL){//(3)北邮校党委管理员
			
			//获得所有的分党委list
			firstPaList = branchService.findChildBranchesById(branchId);	
			
		}
		
		if(currentNews == null) return "error";
		
		return "modifyNews";
	}
	
	public String saveModifyNews(){
		
		HttpServletRequest request = ServletActionContext.getRequest();
		Integer id = (request.getParameter("id") == null) ? null : Integer.parseInt(request.getParameter("id"));
		
		int modifyNewsPageNow = Integer.parseInt(request.getParameter("modifyNewsPageNow"));
		
		HttpSession session = request.getSession();
		
		Admin session_admin = (Admin) session.getAttribute(SessionConstants.SESSION_USER);
		
		Admin admin = adminService.findAdminByAmdinNO(session_admin.getAdminNo());
		
		request.setAttribute("modifyNewsPageNow", modifyNewsPageNow);
		
		if(id == null) return "error";
		if(!admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL) && (secondPa == null || secondPa == -1)) return "error";
		
		this.currentNews = this.branchNewsService.getNewsById(id);
		
		if(currentNews == null ) return "error";
		
		currentNews.setContent(content);
		currentNews.setTitle(title);
		if(admin.getAdminLevel().equals(SessionConstants.ADMIN_FIRST_LEVEL)) currentNews.setBranchId(admin.getAdminManageBranchId());
		else currentNews.setBranchId(secondPa);
		if(!branchNewsService.saveOrUpdate(currentNews)) return "error";
		
		//添加发布成功操作类别，用来在postSuccess.jsp表示操作成功的标志，以达到向不同的页面跳转的功能
		//（注：请和下面语句一起修改和删除）
		//修改新闻成功的标志是3
		request.setAttribute("tag", currentNews.getTag());

		return "saveModifyNews";
	}
	
	public String deleteNews(){
		Integer id = (request.getParameter("id") == null) ? null : Integer.parseInt(request.getParameter("id"));
		
		int modifyNewsPageNow = Integer.parseInt(request.getParameter("pageNow"));
		
		request.setAttribute("modifyNewsPageNow", modifyNewsPageNow);
		if(id == null) return "error";
		BranchNews news = this.branchNewsService.findBranchNewsById(id);
		
		if(news == null) return "error";
		
		request.setAttribute("tag", news.getTag());
		
		if(!this.branchNewsService.deleteNewsById(id)) return "error";
		
		return "deleteNews";
		
	}
	
	/**
	 * 检查支部名称是否存在，若存在，返回"exist"，否则返回"notexist"
	 * @return
	 */
	public String checkBranchName(){
		
		String name = request.getParameter("branchName");
		String result = null;
		if(name != null && name.trim().length() > 0) {
			if(this.branchService.checkName(name.trim())){//名字存在
				result = "exist";
			}else{
				result ="notexist";
			}
		}
		try {
			response.getWriter().write(result);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public String getPosterNameByNo(String no){
		
		if(no == null || no == "") return "";
		
		String name = adminService.findAdminNameByAdminNO(no);
		
		if(name == null) return "";
		
		return name;
		
	}
	
	public String getBranchNameByBranchId(Integer id){
		
		if(id == null || id == -1) return "";
		
		String name = branchService.getBranchName(id);
		
		if(name == null) return "";
		
		return name;
		
	}
	
	public boolean checkBranchInCharge(Integer branchId){
		
		for(Branch b:chargeBranches){
			if(b.getId().equals(branchId)) return true;
		}
		
		return false;
	}
	
}
